﻿
@{
    ViewData["Title"] = "地区管理-系统管理";
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.CurrentMenuP = "Security";
    ViewBag.CurrentMenu = "Area/List";
}
<div class="container-fluid">
    <div class="row">
        <div class="col-md-2">
            <div class="card card-primary card-outline">
                <div class="card-header">省市级菜单</div>
                <div class="card-body">
                    <div id="toolbarcategory" class="btn-group">
                        @if (@ViewBag.AuthorizeKey.CanInsert)
                        {
                            <button id="btn_add" type="button" class="btn btn-primary btn-sm" data-toggle="modal" onclick="ShowEditOrViewCategoryDialog()" data-whatever="新增">
                                <i class="fas fa-plus" aria-hidden="true"></i>新增
                            </button>
                        }
                        @if (@ViewBag.AuthorizeKey.CanUpdate)
                        {
                            <button id="btn_edit" type="button" class="btn btn-info btn-sm" data-toggle="modal" onclick="ShowEditOrViewCategoryDialog('edit')" data-whatever="修改">
                                <i class="fas fa-edit" aria-hidden="true"></i>修改
                            </button>
                        }
                        @if (@ViewBag.AuthorizeKey.CanDelete)
                        {
                            <button id="btn_delete" type="button" class="btn btn-danger btn-sm" onclick="DeleteCategoryByIds()">
                                <i class="fas fa-trash-alt" aria-hidden="true"></i>删除
                            </button>
                        }
                    </div>
                    <div id="tbTreeGrid"></div>
                </div>
                <!-- /.card-body -->
            </div>
            <!-- /.card -->
        </div>
        <div class="col-md-10">
            <div class="card card-primary card-outline">
                <div class="card-header">市级下属菜单</div>
                <div class="card-body">
                    <div id="toolbar" class="btn-group">
                        @if (@ViewBag.AuthorizeKey.CanInsert)
                        {
                            <button id="btn_add" type="button" class="btn btn-primary" data-toggle="modal" onclick="ShowEditOrViewDialog()" data-whatever="新增">
                                <i class="fas fa-plus" aria-hidden="true"></i>新增
                            </button>
                        }
                        @if (@ViewBag.AuthorizeKey.CanUpdate)
                        {
                            <button id="btn_edit" type="button" class="btn btn-secondary" data-toggle="modal" onclick="ShowEditOrViewDialog('edit')" data-whatever="修改">
                                <i class="fas fa-edit" aria-hidden="true"></i>修改
                            </button>
                        }
                        @if (@ViewBag.AuthorizeKey.CanUpdateEnable)
                        {
                            <button type="button" class="btn btn-warning" onclick="EnableByIds('0','/Security/AreaDetail')"><i class=" fa fa-stop-circle"></i>禁用</button>
                            <button type="button" class="btn btn-success" onclick="EnableByIds('1','/Security/AreaDetail')"><i class=" fa fa-play-circle"></i>启用</button>
                        }
                        @if (@ViewBag.AuthorizeKey.CanDeleteSoft)
                        {
                            <button id="btn_delete" type="button" class="btn btn-warning" onclick="DeleteByIds('/Security/AreaDetail/DeleteSoftByIds')">
                                <i class="fas fa-trash-alt" aria-hidden="true"></i>软删除
                            </button>
                        }
                        @if (@ViewBag.AuthorizeKey.CanDelete)
                        {
                            <button id="btn_delete" type="button" class="btn btn-danger" onclick="DeleteByIds('/Security/AreaDetail/DeleteByIds')">
                                <i class="fas fa-trash-alt" aria-hidden="true"></i>删除
                            </button>
                        }


                    </div>
                    <table id="tbGrid"></table>
                </div>
                <!-- /.card-body -->
            </div>
            <!-- /.card -->
        </div>
    </div>
</div>




<!-- 添加/编辑分类信息的弹出层 -->
<div class="modal fade" id="addCategoryFormModal" tabindex="-1" role="dialog" aria-labelledby="addCategoryFormModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form class="form-horizontal" id="frmSubmitCategory" method="post" enctype="multipart/form-data">
                <div class="modal-header bg-primary">
                    <h5 class="modal-title" id="addCategoryFormModalLabel">新增</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="FullName" class="col-form-label col-2">名称:</label>
                                    <input type="text" class="form-control col-10" name="FullName" id="FullName" placeholder="请输入城市名称">
                                </div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="EnCode" class="col-form-label col-2">编码:</label>
                                    <input type="text" class="form-control col-10" name="EnCode" id="EnCode" placeholder="请输入邮政编码">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="ParentId" class="col-form-label col-2">上级:</label>
                                    <select class="form-control select2  col-10" name="ParentId" id="ParentId">
                                        <option value="">==请选择上级菜单==</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="SortCode" class="col-form-label col-2">排序:</label>
                                    <input type="text" class="form-control col-10" name="SortCode" id="SortCode" placeholder="请输入排序号">
                                </div>
                            </div>
                        </div>
                    </div>

                    <input type="hidden" id="Id" name="Id" value="" />
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary btnSave" id="btnSaveCategoryOK"><i class="fa fa-save"></i>保存</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-close"></i>关闭</button>
                </div>
            </form>
        </div>
    </div>
</div>


<!-- 添加/编辑信息的弹出层 -->
<div class="modal fade" id="addFormModal" tabindex="-1" role="dialog" aria-labelledby="addFormModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <form class="form-horizontal" id="frmSubmit" method="post" enctype="multipart/form-data">
                <div class="modal-header bg-primary">
                    <h5 class="modal-title modal-sm" id="addFormModalLabel">新增</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="FullName" class="col-form-label col-2">名称:</label>
                                    <input type="text" class="form-control col-10" name="FullName" id="FullName1" placeholder="请输入城市名称">
                                </div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="EnCode" class="col-form-label col-2">编码:</label>
                                    <input type="text" class="form-control col-10" name="EnCode" id="EnCode1" placeholder="请输入邮政编码">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="ParentId" class="col-form-label col-2">上级:</label>
                                    <select class="form-control select2  col-10" name="ParentId" id="ParentId1">
                                        <option value="">==请选择上级菜单==</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="form-group">
                                <div class="row">
                                    <label for="SortCode" class="col-form-label col-2">排序:</label>
                                    <input type="text" class="form-control col-10" name="SortCode" id="SortCode1" placeholder="请输入排序号">
                                </div>
                            </div>
                        </div>
                    </div>

                    <input type="hidden" id="Id1" name="Id" value="" />
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary btnSave" id="btnSaveOK"><i class="fa fa-save"></i>保存</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-close"></i>关闭</button>
                </div>
            </form>
        </div>
    </div>
</div>

<link rel="stylesheet" href="~/lib/bootstrap-treeview/css/bootstrap-treeview.css" />
<script src="~/lib/bootstrap-treeview/js/bootstrap-treeview.js"></script>
<!-- page script -->
<script>
    $(function () {
        //iCheck for checkbox and radio inputs
        $('input[type="checkbox"].flat-red').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass: 'iradio_minimal',
        })
        InitCategoryTree();
        //1.初始化Table
        var oTable = new TableInit();
        oTable.Init();

        InitDictItem();
        BindSaveCategoryEvent();
        BindSaveEvent();
    });

    //加载数据表格
var $table = $('#tbGrid');
    var TableInit = function () {
        var oTableInit = new Object();
        var keywords = "";
        //初始化Table
        oTableInit.Init = function () {
            //首先取出来用户选择的数据的ID
            var rows = $("#tbTreeGrid").treeview('getSelected');
            //首先取出来值判断用户只能选择一个
            if (rows.length == 0) {
                toastr.warning("请选择分类");
                return;
            }
            $table.bootstrapTable({
                url: '/Security/Area/GetAlltownsViewJson',         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,
                sidePagination: 'server',
                sortable: false,
                queryParams: oTableInit.queryParams,//传递参数（*）
                //search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                //strictSearch: true,
                showColumns: true,                  //是否显示所有的列
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                search: true,
                searchOnEnterKey: true,
                searchText: keywords,
                idField: 'Id',
                columns: [
                    {
                        checkbox: true
                    }, {
                        field: 'FullName',
                        title: '名称',
                        sortable: true,
                        searchable: true,
                    }, {
                        field: 'ParentId',
                        title: '名称',
                        sortable: true,
                        searchable: true,
                    },
                    {
                        field: 'EnabledMark',
                        title: '状态',
                        sortable: true,
                        align: "center",
                        formatter: function (value, row, index) {
                            return value ? '<i class=\"fas fa-toggle-on\" style=\"color:#28a745\">启用</i>' : "<i class=\"fas fa-toggle-off\">禁用</i>"
                        }
                    },{
                        field: 'DeleteMark',
                        title: '删除',
                        sortable: true,
                        align: "center",
                        formatter: function (value, row, index) {
                            return value ? '<i class=\"fas fa-toggle-on\" style=\"color:#f00\">是</i>' : "<i class=\"fas fa-toggle-off\">否</i>"
                        }
                    }
                ],
                onSearch: function (text) {
                    keywords = text;
                    return true;
                },
            });
        };

        //得到查询的参数
        oTableInit.queryParams = function (params) {
            var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                limit: params.limit,   //页面大小
                offset: params.offset,  //页码
                order: params.order,
                sort: params.sort,
                search: $("input[ name='search_text' ] ").val(), //定义传输的搜索参数
            };
            return temp;
        };
        return oTableInit;
    };


    //初始化数据字典
    function InitDictItem() {
        $("#ParentId").bindSelect({
            url: "/Security/Area/FindTreeSelectJsonCity",
        });
    }

    //初始化字典数据
    function InitItemsDetail() {
        $("#ParentId1").bindSelect({
            url: "/Security/Area/FindTreeSelectJsonTowns",
        });
    }

    //加载分类树
    function InitCategoryTree() {
        var treeUrl = "/Security/Area/GetAllTreeViewJson";
        $.ajax({
            url: treeUrl,
            data: "",
            dataType: 'json',//服务器返回json格式数据
            type: 'get',//HTTP请求类型
            timeout: 100000,//超时时间设置为10秒；
            success: function (data) {
                $('#tbTreeGrid').treeview({
                    data: data,
                    levels: 5,
                    multiSelect: false,
                    showIcon: false,
                    showCheckbox: false,
                    showTags: false,
                    onNodeSelected: function (event, node) { //选择节点
                        $table.bootstrapTable('refresh');
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                toastr.warning("操作失败：" + errorThrown);
            }
        });
    }

    //新增、修改或查看明细信息（绑定显示数据）
    function ShowEditOrViewCategoryDialog(view) {
        if (view != null) {
            //首先取出来用户选择的数据的ID
            var rows = $("#tbTreeGrid").treeview('getSelected');
            //首先取出来值判断用户只能选择一个
            if (rows.length == 0) {
                toastr.warning("请选择一条记录");
                return;
            } else if (rows.length > 1) {
                toastr.warning("每次只能修改/查看一条记录，你已经选择了<font color='red'  size='6'>" + rows.length + "</font>条");
                return;
            }
        }
        if (view == null) {
            //处理修改的信息
            $('#addCategoryFormModal').modal('show');  //手动显示
            $('#addCategoryFormModalLabel').find('.modal-title').text("新增");
            $("#Id").val("");
        } else if (view == "edit") {
            //处理修改的信息
            $('#addCategoryFormModal').modal('show');  //手动显示
            $('#addCategoryFormModalLabel').find('.modal-title').text("编辑");
            //绑定修改详细信息的方法
            BindEditCategoryInfo();
        }
    }

    //绑定编辑详细信息的方法
    function BindEditCategoryInfo() {
        //首先用户发送一个异步请求去后台实现方法
        var rows = $("#tbTreeGrid").treeview('getSelected');
        var ID = $("#tbTreeGrid").treeview('getSelected')[0].tags;  //获取到了用用户选择的ID
        $.getJSON("/Security/Area/GetById?r=" + Math.random() + "&id=" + ID, function (info) {
            //赋值有几种方式：.datebox('setValue', info.Birthday);.combobox('setValue', info.Status);.val(info.Name);
            $("#Id").val(info.ResData.Id);
            $("#frmSubmitCategory").formSerialize(info.ResData);
        });
    }
    //绑定保存按钮的事件
    function BindSaveCategoryEvent() {
        $("#btnSaveCategoryOK").click(function () {
            $("#frmSubmitCategory").validate({
                rules: {
                    FullName: {
                        required: true,
                        minlength: 1
                    }
                },
                messages: {
                    FullName: {
                        required: "请输入城市名称",
                        minlength: "城市名称至少1个字符"
                    }
                },
                errorClass: 'help-block help-block-error',
                focusInvalid: true,
                //unhighlight: function (element, errorClass, validClass) { //验证通过
                //    $(element).tooltip('destroy').removeClass(errorClass);
                //},
                highlight: function (element) {//验证未通过
                    $(element).closest('.form-group').addClass('has-error');
                },
                success: function (label, element) {
                    $(element).closest('.form-group').removeClass('has-error');
                    //label.remove();
                    $(element).attr("title", "").tooltip("hide");
                    //alert(element);
                },
                errorPlacement: function (error, element) {
                    //element.parent('div').append(error);
                    if ($(element).next("div").hasClass("tooltip")) {
                        $(element).attr("data-original-title", $(error).text()).tooltip("show");
                    } else {
                        $(element).attr("title", $(error).text()).tooltip("show");
                    }
                },
                submitHandler: function (form) {
                    var postData = {
                        "Id": $("#Id").val(),
                        "FullName": $("#FullName").val(),
                        "EnCode": $("#EnCode").val(),
                        "ParentId": $("#ParentId").val(),
                        "SortCode": $("#SortCode").val()
                    };
                    var keyValue = $("#Id").val();
                    var reqUrl = "/Security/Area/Insert";
                    if (keyValue != "" && keyValue != null && keyValue != "null") {
                        reqUrl = "/Security/Area/Update?id=" + keyValue;
                    }
                    $.ajax({
                        url: reqUrl,
                        data: postData,
                        dataType: 'json',//服务器返回json格式数据
                        type: 'post',//HTTP请求类型
                        timeout: 100000,//超时时间设置为10秒；
                        success: function (data) {
                            //服务器返回响应，根据响应结果，分析是否登录成功；
                            if (data.Success) {
                                $('#addCategoryFormModal').modal('hide');  //手动关闭
                                $("#frmSubmitCategory")[0].reset();
                                toastr.success("操作成功");
                                setTimeout(function () {
                                    InitCategoryTree();
                                }, 1500);
                            } else {
                                toastr.warning("操作失败：" + data.ErrMsg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            toastr.warning("操作失败：" + errorThrown);
                        }
                    });
                }
            });
        });
    }

    function DeleteCategoryByIds() {
        //得到用户选择的数据的ID
        var ID = $("#tbTreeGrid").treeview('getSelected')[0].tags;  //获取到了用用户选择的ID
        if (ID.length >= 1) {
            var postData = { ids: ID };
            swal({
                title: "操作提示",
                text: "您确定删除选定的记录吗？",
                icon: "warning",
                closeOnClickOutside: false,
                buttons: {
                    cancel: {
                        text: "取消",
                        visible: true,
                        closeModal: true,
                    },
                    confirm: {
                        text: "是的，执行删除！",
                        value: "ok",
                        className: "swal-button-confirm"
                    },
                }
            }).then(function (value) {
                if (value == "ok") {
                    $.ajax({
                        url: '/Security/Area/DeleteByIds',
                        data: postData,
                        dataType: 'json',//服务器返回json格式数据
                        type: 'post',//HTTP请求类型
                        timeout: 100000,//超时时间设置为10秒；
                        success: function (data) {
                            //服务器返回响应，根据响应结果，分析是否登录成功；
                            if (data.Success) {
                                toastr.success("删除成功");
                                setTimeout(function () {
                                    $("#tbTreeGrid").treeview('refresh');
                                }, 1000);
                            } else {
                                toastr.warning("操作失败：" + data.ErrMsg);
                            }
                        },
                        error: function (data) {
                            toastr.warning("删除异常,请重新试试");
                        }
                    });
                }
            });
        } else {
            toastr.warning("请选择你要删除的数据");
        }
    }
    //新增、修改或查看明细信息（绑定显示数据）
    function ShowEditOrViewDialog(view) {
        if (view != null) {
            //首先取出来用户选择的数据的ID
            var rows = $table.bootstrapTable('getSelections');
            //首先取出来值判断用户只能选择一个
            if (rows.length == 0) {
                toastr.warning("请选择一条记录");
                return;
            }
            else if (rows.length > 1) {
                toastr.warning("每次只能修改/查看一条记录，你已经选择了<font color='red'  size='6'>" + rows.length + "</font>条");
                return;
            }
        }
        if (view == null) {
            //处理修改的信息
            $('#addFormModal').modal('show');  //手动显示
            $('#addFormModal').find('.modal-title').text("新增");
            $("#Id").val("");
            InitItemsDetail();
        } else if (view == "edit") {
            //处理修改的信息
            $('#addFormModal').modal('show');  //手动显示
            $('#addFormModal').find('.modal-title').text("编辑");
            InitItemsDetail();
            //绑定修改详细信息的方法
            BindEditInfo();
        }

    }

    //绑定编辑详细信息的方法
    function BindEditInfo() {
        //首先用户发送一个异步请求去后台实现方法
        var ID = $table.bootstrapTable('getSelections')[0].Id;  //获取到了用用户选择的ID
        $.getJSON("/Security/Area/GetById?r=" + Math.random() + "&id=" + ID, function (info) {
            //赋值有几种方式：.datebox('setValue', info.Birthday);.combobox('setValue', info.Status);.val(info.Name);
            $("#Id").val(info.ResData.Id);
            $("#frmSubmit").formSerialize(info.ResData);
            $("#ParentId1").val(info.ResData.ParentId);
            $("#ItemsDetailSortCode").val(info.ResData.SortCode);
            $("#ItemsDetailEnabledMark").val(info.ResData.EnabledMark);
            $("#ItemsDetailDescription").val(info.ResData.Description);
        });
    }
    //绑定保存按钮的事件
    function BindSaveEvent() {
        $("#btnSaveOK").click(function () {
            $("#frmSubmit").validate({
                rules: {
                    FullName: {
                        required: true,
                        minlength: 2
                    },
                    EnCode: {
                        required: true,
                        minlength: 2
                    }
                },
                messages: {
                    FullName: {
                        required: "请输入地区名称",
                        minlength: "菜单名称至少2个字符"
                    },
                    EnCode: {
                        required: "请输入地区邮政编码",
                        minlength: "功能编码至少2个字符"
                    }
                },
                errorClass: 'help-block help-block-error',
                focusInvalid: true,
                //unhighlight: function (element, errorClass, validClass) { //验证通过
                //    $(element).tooltip('destroy').removeClass(errorClass);
                //},
                highlight: function (element) {//验证未通过
                    $(element).closest('.form-group').addClass('has-error');
                },
                success: function (label, element) {
                    $(element).closest('.form-group').removeClass('has-error');
                    //label.remove();
                    $(element).attr("title", "").tooltip("hide");
                    //alert(element);
                },
                errorPlacement: function (error, element) {
                    //element.parent('div').append(error);
                    if ($(element).next("div").hasClass("tooltip")) {
                        $(element).attr("data-original-title", $(error).text()).tooltip("show");
                    } else {
                        $(element).attr("title", $(error).text()).tooltip("show");
                    }
                },
                submitHandler: function (form) {
                    var postData = {
                        "Id": $("#Id1").val(),
                        "FullName": $("#FullName1").val(),
                        "EnCode": $("#EnCode1").val(),
                        "ParentId": $("#ParentId1").val(),
                        "SortCode": $("#SortCode1").val()
                    };
                    var keyValue = $("#Id").val();
                    var reqUrl = "/Security/Area/Insert";
                    if (keyValue != "" && keyValue != null && keyValue != "null") {
                        reqUrl = "/Security/Area/Update?id=" + keyValue;
                    }
                    $.ajax({
                        url: reqUrl,
                        data: postData,
                        dataType: 'json',//服务器返回json格式数据
                        type: 'post',//HTTP请求类型
                        timeout: 100000,//超时时间设置为10秒；
                        success: function (data) {
                            //服务器返回响应，根据响应结果，分析是否登录成功；
                            if (data.Success) {
                                $('#addFormModal').modal('hide');  //手动关闭
                                $("#frmSubmit")[0].reset();
                                toastr.success("操作成功");
                                setTimeout(function () {
                                    $table.bootstrapTable('refresh');
                                }, 1500);
                            } else {
                                toastr.warning("操作失败：" + data.ErrMsg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            toastr.warning("操作失败：" + errorThrown);
                        }
                    });
                }
            });
        });
    }


</script>